package org.feng.util;

import lombok.extern.slf4j.Slf4j;
import org.feng.annotions.SensitiveEntity;
import org.feng.sensitive.AbstractSensitive;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 敏感信息处理工具类
 *
 * @version v1.0
 * @author: fengjinsong
 * @date: 2023年08月25日 23时42分
 */
@Slf4j
public class SensitiveUtil {

    /**
     * 是否是敏感信息实体，带有{@link SensitiveEntity}注解的都是敏感实体
     *
     * @param object 需要判断对象
     * @return 是敏感实体返回true；否则返回false
     */
    public static boolean isSensitiveEntity(Object object) {
        return object.getClass().isAnnotationPresent(SensitiveEntity.class);
    }


    public static void decryptFieldValue(Field field, Object object, AbstractSensitive sensitive) {
        field.setAccessible(true);
        // 解密
        try {
            Object fieldValue = field.get(object);
            if (Objects.nonNull(fieldValue)) {
                field.set(object, sensitive.decrypt(fieldValue.toString()));
            }
        } catch (IllegalAccessException e) {
            log.error("解密失败", e);
            throw new RuntimeException("解密失败");
        }
        field.setAccessible(false);
    }

    public static void encryptFieldValue(Field field, Object object, AbstractSensitive sensitive) {
        field.setAccessible(true);
        // 加密
        try {
            Object fieldValue = field.get(object);
            if (Objects.nonNull(fieldValue)) {
                field.set(object, sensitive.encrypt(fieldValue.toString()));
            }
        } catch (IllegalAccessException e) {
            log.error("加密失败", e);
            throw new RuntimeException("加密失败");
        }
        field.setAccessible(false);
    }

    /**
     * 11位手机中间加星号脱敏
     *
     * @param phone 手机号
     * @return 加星号的手机
     */
    public static String maskedPhone(String phone) {
        return new StringBuilder(phone).replace(3, 7, "****").toString();
    }

    /**
     * 邮箱脱敏
     *
     * @param email 邮箱
     * @return 加星号的邮箱
     */
    public static String maskedEmail(String email) {
        return new StringBuilder(email).replace(1, email.indexOf('@') - 1, "***").toString();
    }
}
